import jwt from 'jsonwebtoken';
import { generateVerifyCode } from '../utils/verifyCodeGenerator.js';

// 存储验证码的Map (sessionId -> {code, expiry})
const verifyCodeStore = new Map();

// 生成验证码
export const getVerifyCode = (req, res) => {
  try {
    const sessionId = Date.now().toString(36) + Math.random().toString(36).substring(2);
    const { text } = generateVerifyCode();
    verifyCodeStore.set(sessionId, {
      code: text,
      expiry: Date.now() + 5 * 60 * 1000
    });
    setTimeout(() => {
      verifyCodeStore.delete(sessionId);
    }, 5 * 60 * 1000);
    res.json({
      success: true,
      sessionId,
      code: text // 直接返回验证码字符串
    });
  } catch (error) {
    console.error('生成验证码错误:', error);
    res.status(500).json({ success: false, message: '生成验证码失败' });
  }
};

// 用户登录
export const login = (req, res) => {
  try {
    const { username, password, verifyCode, sessionId } = req.body;
    
    // 验证必填字段
    if (!username || !password || !verifyCode || !sessionId) {
      return res.status(400).json({ success: false, message: '请填写完整信息' });
    }
    
    // 验证验证码
    const storedVerifyCode = verifyCodeStore.get(sessionId);
    if (!storedVerifyCode || storedVerifyCode.expiry < Date.now()) {
      return res.status(400).json({ success: false, message: '验证码已过期' });
    }
    
    if (verifyCode.toLowerCase() !== storedVerifyCode.code.toLowerCase()) {
      return res.status(400).json({ success: false, message: '验证码错误' });
    }
    
    // 验证用户名和密码
    const user = users.find(u => u.username === username && u.password === password);
    if (user) {
      // 生成JWT令牌
      const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret';
      if (process.env.NODE_ENV === 'production' && !process.env.JWT_SECRET) {
        console.warn('警告: 生产环境中未设置JWT_SECRET环境变量');
      }
      
      const token = jwt.sign(
        { id: user.id, username: user.username },
        JWT_SECRET,
        { expiresIn: '1d' }
      );
      
      // 登录成功后删除验证码
      verifyCodeStore.delete(sessionId);
      
      return res.json({
        success: true,
        message: '登录成功',
        token,
        user: { id: user.id, username: user.username }
      });
    } else {
      return res.status(401).json({ success: false, message: '用户名或密码错误' });
    }
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ success: false, message: '登录失败' });
  }
};

// 简单的用户存储（实际项目中应使用数据库）
const users = [];

// 用户注册
export const register = (req, res) => {
  try {
    const { username, email, password } = req.body;
    
    // 验证必填字段
    if (!username || !email || !password) {
      return res.status(400).json({ success: false, message: '请填写完整信息' });
    }
    
    // 检查用户是否已存在
    const existingUser = users.find(user => user.username === username || user.email === email);
    if (existingUser) {
      return res.status(400).json({ success: false, message: '用户名或邮箱已存在' });
    }
    
    // 创建新用户（实际项目中应该加密密码）
    const newUser = {
      id: Date.now(),
      username,
      email,
      password, // 实际项目中应使用bcrypt加密
      createdAt: new Date()
    };
    
    users.push(newUser);
    
    res.json({
      success: true,
      message: '注册成功',
      user: {
        id: newUser.id,
        username: newUser.username,
        email: newUser.email
      }
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ success: false, message: '注册失败' });
  }
};